﻿<%@ WebHandler Language="C#" Class="AuthorityPostionManage" %>

using System;
using System.Web;
using System.Data;
using System.Text;
using System.IO;
using Chenxin.Lib.Utility;
using System.Collections.Generic;

public class AuthorityPostionManage : AjaxHandlerBase
{
    public AuthorityPostionManage()
    {
        htTypePermit.Add("add", Constants.Permit_Hr_AddPositionRelation);//添加职务职权对应
        htTypePermit.Add("del", Constants.Permit_Hr_DelPositionRelation);//删除职务职权对应
    }

    override public void RequestProcess(HttpContext context)
    {
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";

        string optype = context.Request.Params["op"];
        switch (optype.ToLower())
        {
            case "getlist":     //得到页面查询数据Table
                GetList(context);
                break;
            case "del":         //根据RecordId删除数据
                DelAuthorityPostion(context);
                break;
            case "add":
                AddAuthorityPostion(context);       //添加职权职务数据
                break;
            case "getofficename":           //得到职务名称
                GetOfficeName(context);
                break;
        }
    }
    
    //根据公司ID得到职务名称
    private void GetOfficeName(HttpContext context)
    {
        try
        {
            string companyid = context.Request.Params["companyid"];
            
            string strSql = string.Format("ItemKey= 'System.Position' and ItemValue not in (select OfficeName from Chenxin_Main.dbo.HR_Rel_Office where CompanyID='{0}') and CompanyID='{0}'", companyid);
            DataSet ds = Chenxin.Lib.House.DAL.DataDictionary.GetList(strSql, "");
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            if (ds.Tables.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        sb.AppendFormat("'{0}',",dr["ItemValue"].ToString());
                    }
                    sb.Remove(sb.Length - 1, 1);
                }
            }
            context.Response.Write(string.Format("{{success:'1',msg:'',data:{{items:[{0}]}}}}",sb.ToString()));
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message));
        }
    }
    

    //添加职权职务数据
    private void AddAuthorityPostion(HttpContext context)
    {
        try
        {
            string strSql = "";
            string terms = context.Request.Params["postname"];
            string companyid = context.Request.Params["companyid"];
            string pos = context.Request.Params["OfficeNameList"];
            string[] array = pos.Split(',');

            foreach (string s in array)
            {
                if (s != "请选择")
                    strSql += string.Format("insert into HR_Rel_Office values(newid(),'{0}','{1}','{2}',getdate());", terms, s, companyid);
            }

            bool flag = Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.ExecuteSQL(strSql);
            if (flag)
            {
                context.Response.Write(string.Format("{{success:'1',msg:'添加成功！',data:''}}"));
                //添加操作日志
                AddLog("" + CurrentUserInfo.UserName + "添加职权职务设定",
                        OperationType.OperationTypeComboList()["OprType_PosTermsAdd"].ToString());
            }
            else
                context.Response.Write(string.Format("{{success:'0',msg:'操作失败，请与IT部联系！',data:''}}"));
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message));
        }
    }
    
    
    //删除数据
    private void DelAuthorityPostion(HttpContext context)
    {
        try
        {
            string recordid = context.Request["modelid"];
            
            string strSql = string.Format("delete from HR_Rel_Office where RecodID='{0}'", recordid);
            bool flag = Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.ExecuteSQL(strSql);
            if (flag)
            {
                context.Response.Write(string.Format("{{success:'1',msg:'删除成功！',data:''}}"));
                //添加操作日志
                AddLog("" + CurrentUserInfo.UserName + "删除职权职务设定",
                        OperationType.OperationTypeComboList()["OprType_PosTermsDel"].ToString());
            }
            else
                context.Response.Write(string.Format("{{success:'0',msg:'无此数据，请确认！',data:''}}"));
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message));
        }
    }

    //得到查询数据
    private void GetList(HttpContext context)
    {
        try
        {
            int iPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            int iPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);//页记录数

            string fieldlist = "RecodID,PostName,OfficeName,DepartName";
            string fieldtablelist = "RecodID,PostName,OfficeName,DepartName";
            string orderfield = "HR_Rel_Office.AddTime desc";

            Guid cityId = (string.IsNullOrEmpty(context.Request["cityid"])) ? Guid.Empty : new Guid(context.Request["cityid"]);
            Guid companyId = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            if (companyId != Guid.Empty)
                sb.AppendFormat(" AND HR_Rel_Office.CompanyID = '{0}'", companyId);
            else if (cityId != Guid.Empty)
                sb.AppendFormat(" AND CityId = '{0}'", cityId);
            else
                sb.AppendFormat(" AND HR_Rel_Office.CompanyID = '{0}'", CurrentUserInfo.CompanyId);

            if (!string.IsNullOrEmpty(context.Request.Params["postname"]))
                sb.AppendFormat(" and PostName='{0}'", context.Request.Params["postname"]);


            System.Text.StringBuilder sb1 = new System.Text.StringBuilder();
            //查看所有权限
            if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewAllAuthorityPostion))
            {
                sb1.Append(" (1=1) ");
            }
            //查看城市权限
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewCityAuthorityPostion))
            {
                sb1.AppendFormat(" CityId= '{0}' ", CurrentUserInfo.CityId);
            }
            //查看公司权限
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewCompanyAuthorityPostion))
            {
                sb1.AppendFormat(" HR_Rel_Office.CompanyID= '{0}' ", CurrentUserInfo.CompanyId);
            }
            else
                sb1.Append(" (1=0) ");

            if (!String.IsNullOrEmpty(sb.ToString()))
                sb1.Append(sb.ToString());
            
            System.Data.DataSet list = null;
            list = Chenxin.Lib.Hr.DAL.Hr_PersonnelTransferInfo.GetList(
                iPageIndex, iPageSize, orderfield, "HR_Rel_Office left join Hr_DepartmentInfo on HR_Rel_Office.CompanyID = Hr_DepartmentInfo.DepartId", sb1.ToString(), fieldlist, fieldtablelist, true);
            int count = (int)list.Tables[1].Rows[0][0];
            string strHtml = "";
            if (!GetKeyListHtml(list, out strHtml))
            {
                context.Response.Write(string.Format("{{success:'0',msg:'{0}',data:''}}", "生成HTML错误:" + strHtml));
            }
            list.Dispose();
            list = null;
            context.Response.Write(string.Format("{{success:'1',msg:'{0}',data:{{count:'{1}',data:'{2}'}}}}", "成功", count, strHtml));
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message));
        }
    }

    //得到Table的HTML及总条数
    private bool GetKeyListHtml(System.Data.DataSet dslist, out string strHtml)
    {
        try
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("<table width=\"100%\" height=\"100%\" cellspacing=\"1\" class=\"tabsorternew\" id=\"report\">");
            sb.Append("<thead><tr>");
            sb.Append("<th >职权</th>");
            sb.Append("<th >职务</th>");
            sb.Append("<th >公司</th>");
            //sb.Append("<th >操作</th>");
            sb.Append("</tr></thead><tbody>");

            foreach (System.Data.DataRow row in dslist.Tables[0].Rows)
            {
                sb.AppendFormat("<tr id=\"{0}\" class=\"tr_settinglist\">", row["RecodID"].ToString());
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "PostName", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "OfficeName", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "DepartName", ""));
                //sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "EmpLevel_O", ""));
                sb.Append("</tr>");
            }

            sb.Append("</tbody></table>");
            strHtml = sb.ToString();
            return true;
        }
        catch (Exception ex)
        {
            strHtml = ex.Message;
            return false;
        }
    }
}